package com.mycompany.biblio.business;

import com.mycompany.biblio.model.User;
import java.util.List;
import javax.ejb.EJB;
import javax.persistence.*;
import javax.ejb.Stateless;


@Stateless
public class UserDAO 
{

    // ======================================
    // =             Attributes             =
    // ======================================
    @PersistenceContext(unitName = "jsfExamplePU")
    private EntityManager em;
    
    @EJB
    SecurityService securityService;
    

    // ======================================
    // =           Public Methods           =
    // ======================================

    
    public User findByUsername(String username) {
        Query query = em.createNamedQuery(User.FIND_BY_USERNAME).setParameter("username", username);
        List<Object> list = query.getResultList();
        if (!list.isEmpty() && list.iterator().hasNext())
        {
            return (User)list.iterator().next();
        }
        else
            return null;
    }
    
    public List<User> findAllFriends()
    {
        User user = securityService.getCurrentUser();
        Query query = em.createNamedQuery(User.FIND_ALL_FRIENDS).setParameter("user", user);
        return query.getResultList();
    }

    public User create(User user) {
        em.persist(user);
        return user;
    }

    public User update(User user) 
    {
        return em.merge(user);
    }

}
